<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="default"
          @click="handlePush"
          class="mb10"
          v-if="hmPermissions.includes('village:household:push')"
          >批量推送</el-button
        >
        <el-select
          style="margin-left: 10px; width: 120px;"
          v-model="query.auditStatus"
          placeholder="状态选择"
          class="handle-select mr10"
          @change="checkStatus"
          clearable
        >
          <el-option
            v-for="(item, index) in auditStatusArr"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>

        <common-item1
          :query="query"
          :streetList="streetList"
          :communityList="communityList"
          :villageList="villageList"
          :showInput="showInput"
          @visibleChangeStreet="visibleChangeStreet"
          @changeStreet="changeStreet"
          @visibleChangeCommunity="visibleChangeCommunity"
          @changeCommunity="changeCommunity"
          @visibleChangeVillage="visibleChangeVillage"
          @changeVillage="changeVillage"
          @search="handleSearch"
        />
        <template>
          <el-select
            style="width:120px;"
            v-model="enableStatus"
            placeholder="是否空置"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>

        <el-button
          type="primary"
          style="margin-left:10px;"
          @click="handleSearch"
          >查询</el-button
        >
        <el-button
          type="default"
          @click="handlePush"
          v-if="hmPermissions.includes('village:household:push')"
          >推送</el-button
        >
        <el-button
          type="default"
          class="handle-del mr10"
          @click="delAllSelection"
          v-if="hmPermissions.includes('village:household:delete')"
          >删除</el-button
        >
        <el-button
          type="default"
          v-if="hmPermissions.includes('village:household:save')"
          @click="handleIncrease"
          >新增</el-button
        >

        <el-button
          type="default"
          @click="handleExport"
          v-if="hmPermissions.includes('village:household:export')"
          >导出</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="householdNo"
          align="center"
          label="户室编号"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="rfid"
          label="芯片编号"
        ></el-table-column>

        <el-table-column
          prop="villageName"
          align="center"
          label="小区名称"
        ></el-table-column>

        <el-table-column
          prop="buildingNo"
          align="center"
          label="楼栋号"
        ></el-table-column>

        <el-table-column
          prop="unitNo"
          align="center"
          label="单元号"
        ></el-table-column>

        <el-table-column
          prop="houseNumber"
          align="center"
          label="门牌号"
        ></el-table-column>

        <el-table-column
          prop="auditStatusName"
          align="center"
          label="审核状态"
        ></el-table-column>

        <el-table-column
          prop="vacant"
          align="center"
          label="是否空置"
        ></el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleEdit(scope.$index, scope.row)"
              v-if="hmPermissions.includes('village:household:update')"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              v-if="hmPermissions.includes('village:household:delete')"
              >删除</el-button
            >
            <el-button
              v-if="
                scope.row.auditStatus == 0 &&
                  hmPermissions.includes('village:household:update')
              "
              type="text"
              @click="handleChecked(scope.$index, scope.row, 1)"
              >审核通过</el-button
            >
            <el-button
              v-if="
                scope.row.auditStatus == 0 &&
                  hmPermissions.includes('village:household:update')
              "
              type="text"
              @click="handleChecked(scope.$index, scope.row, 2)"
              >审核不通过</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20, 30]"
          @size-change="handleSizeChange"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="auto"
        :rules="rules"
      >
        <el-form-item label="二维码编号" prop="qrCode">
          <el-input v-model="editForm.qrCode"></el-input>
        </el-form-item>

        <el-form-item label="芯片编号">
          <el-input v-model="editForm.rfid"></el-input>
        </el-form-item>

        <el-form-item label="户主姓名">
          <el-input v-model="editForm.householder"></el-input>
        </el-form-item>

        <el-form-item label="户主电话">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>

        <el-form-item label="小区名称" prop="villageName">
          <el-input v-model="editForm.villageName"></el-input>
        </el-form-item>

        <el-form-item label="楼栋号" prop="buildingNo">
          <el-input v-model="editForm.buildingNo"></el-input>
        </el-form-item>

        <el-form-item label="单元号" prop="unitNo">
          <el-input v-model="editForm.unitNo"></el-input>
        </el-form-item>

        <el-form-item label="门牌号" prop="houseNumber">
          <el-input v-model="editForm.houseNumber"></el-input>
        </el-form-item>

        <el-form-item label="是否空置">
          <template>
            <el-radio v-model="editForm.enableStatus" label="0">空置</el-radio>
            <el-radio v-model="editForm.enableStatus" label="1"
              >非空置</el-radio
            >
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog title="新增" :visible.sync="addVisible" width="50%">
      <el-form ref="addForm" :model="addForm" label-width="auto" :rules="rules">
        <el-form-item label="二维码编号" prop="qrCode">
          <el-input v-model="addForm.qrCode"></el-input>
        </el-form-item>
        <el-form-item label="芯片编号">
          <el-input v-model="addForm.rfid"></el-input>
        </el-form-item>

        <el-form-item label="户主姓名">
          <el-input v-model="addForm.householder"></el-input>
        </el-form-item>

        <el-form-item label="户主电话">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>

        <el-form-item label="小区名称" prop="villageName">
          <el-input v-model="addForm.villageName"></el-input>
        </el-form-item>

        <el-form-item label="楼栋号" prop="buildingNo">
          <el-input v-model="addForm.buildingNo"></el-input>
        </el-form-item>

        <el-form-item label="单元号" prop="unitNo">
          <el-input v-model="addForm.unitNo"></el-input>
        </el-form-item>

        <el-form-item label="门牌号" prop="houseNumber">
          <el-input v-model="addForm.houseNumber"></el-input>
        </el-form-item>

        <el-form-item label="是否空置">
          <template>
            <el-radio v-model="addForm.enableStatus" label="0">空置</el-radio>
            <el-radio v-model="addForm.enableStatus" label="1">非空置</el-radio>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 审核不通过原因 -->
    <el-dialog
      title="审核不通过原因"
      :visible.sync="checkedVisible"
      width="50%"
    >
      <el-form ref="addForm" :model="addForm" label-width="auto" :rules="rules">
        <el-form-item label="原因" prop="qrCode">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入审核不通过原因"
            v-model="textarea"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelCheckedSave">取 消</el-button>
        <el-button type="primary" @click="handleCheckedSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import util from "utils/util";
import { mapGetters } from "vuex";
import NProgress from "nprogress";
import { commonItem1 } from "../../common/commonItem1/common-item1.js";
export default {
  name: "housemanage",
  data() {
    return {
      options: [
        {
          value: "0",
          label: "是",
        },
        {
          value: "1",
          label: "否",
        },
      ],
      enableStatus: "",
      hmPermissions: [],
      textarea: "",
      checkedVisible: false,
      ids: [],
      auditStatusArr: ["待审核", "审核通过", "审核不通过"],
      query: {
        streetId: "",
        communityId: "",
        villageId: "",

        streetName: "",
        communityName: "",
        villageName: "",

        auditStatus: "",
        pageIndex: 1,
        pageSize: 20,

        buildingNum: "",
        unitNum: "",
        houseNum: "",
        villageName: "",
      },
      showInput: true,
      streetList: [],
      communityList: [],
      villageList: [],
      tableData: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      addVisible: false,
      pageTotal: 0,
      form: {},
      rules: {
        qrCode: [{ required: true, message: "必填不能为空", trigger: "blur" }],
        villageName: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        buildingNo: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
        unitNo: [{ required: true, message: "必填不能为空", trigger: "blur" }],

        houseNumber: [
          { required: true, message: "必填不能为空", trigger: "blur" },
        ],
      },
      addForm: {
        qrCode: "",
        rfid: "",
        householder: "",
        mobile: "",
        villageName: "",
        buildingNo: "",
        unitNo: "",
        houseNumber: "",
        enableStatus: "",
        memo: "",
      },
      editForm: {
        id: "",
        qrCode: "",
        rfid: "",
        householder: "",
        mobile: "",
        villageName: "",
        buildingNo: "",
        unitNo: "",
        houseNumber: "",
        enableStatus: "",
        memo: "",
      },
      idx: -1,
      id: -1,
    };
  },
  created() {
    this.getData({});
    this.hmPermissions = this.permissions;
  },
  components: {
    "common-item1": () => import("../../common/commonItem1/common-item1.vue"),
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  watch: {
    editVisible(newBool, oldBool) {
      if (newBool === false) {
        this.addForm.enableStatus =
          this.addForm.enableStatus === null ? null : "";
      }
    },
    "$route.path": function(newVal, oldVal) {
      if (newVal == "/house-manage") {
        this.hmPermissions = this.permissions;
      }
    },
    // 刷新浏览器时触发
    permissions: function(newVal, oldVal) {
      this.hmPermissions = newVal;
    },
  },
  methods: {
    // 推送
    handlePush() {
      NProgress.start();
      this.$axios
        .post("/village/household/pushHousehold", {
          villageId: this.query.villageId,
          ids: this.ids,
        })
        .then(({ data: res }) => {
          console.log(res);
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message.success("推送完成");
          NProgress.done();
        })
        .catch((err) => {});
    },
    ...commonItem1,
    // 获取 easy-mock 的模拟数据
    getData({ villageId = "" }) {
      this.$axios
        .get("/village/household/page", {
          params: {
            page: this.query.pageIndex,
            limit: this.query.pageSize,
            auditStatus: this.query.auditStatus,
            villageId,
            buildingNo: this.query.buildingNum,
            unitNo: this.query.unitNum,
            houseNumber: this.query.houseNum,
            enableStatus: this.enableStatus,
            villageName:
              this.showInput == false ? "" : this.query.villageName.trim(),
          },
        })
        .then(({ data: res }) => {
          console.log("户室管理", res);
          if (res.code != 0) {
            return;
          }
          res.data.list.map((item, index) => {
            var pageIndex = this.query.pageIndex;
            item.index = index + 1 + (pageIndex - 1) * this.query.pageSize;
            if (item.enableStatus == 1) {
              item.vacant = "否";
            } else if (item.enableStatus == 0) {
              item.vacant = "是";
            }

            if (item.auditStatus == 0) {
              item.auditStatusName = "待审核";
            } else if (item.auditStatus == 1) {
              item.auditStatusName = "审核通过";
            } else if (item.auditStatus == 2) {
              item.auditStatusName = "审核不通过";
            }
            if (item.enableStatus == 0) {
              item.statusName = "已入住";
            } else if (item.enableStatus == 1) {
              item.statusName = "未入住";
            }
          });
          this.pageTotal = res.data.total || 0;
          this.tableData = res.data.list;
        })
        .catch(() => {});
    },

    checkStatus(status) {
      console.log(status);
      this.query.buildingNum = "";
      this.query.unitNum = "";
      this.query.houseNum = "";
      this.query.villageName = "";
      this.enableStatus = "";

      this.$set(this.query, "auditStatus", status);
      this.$set(this.query, "pageIndex", 1);

      this.getData({ villageId: this.query.villageId });
    },
    // 触发查询按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      if (
        this.query.villageName.trim() == "" &&
        this.query.villageId.trim() == "" &&
        this.enableStatus == ""
      ) {
        return this.$message.warning({
          message: "请先选择查询条件",
          duration: 1500,
        });
      }

      this.getData({
        villageId: this.query.villageId,
      });
    },
    // 导出
    handleExport() {
      if (
        !Boolean(this.query.streetId) &&
        this.query.villageName.trim() == "" &&
        this.enableStatus == ""
      ) {
        return this.$message.warning({
          message: "请选择导出条件",
          duration: 1500,
        });
      }

      NProgress.start();
      this.$axios
        .get("/village/household/export", {
          params: {
            auditStatus: this.query.auditStatus,
            villageId: this.query.villageId,
            enableStatus: this.enableStatus,
            villageName:
              this.showInput == false ? "" : this.query.villageName.trim(),
          },
          responseType: "blob",
        })
        .then((res) => {
          if (res.data.type != "application/vnd.ms-excel") {
            NProgress.done();
            return this.$message.warning({
              message: "数据超过6000条不允许导出",
              duration: 1500,
            });
          }

          // 导出excel表格
          const link = document.createElement("a");
          let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          let num = "";
          for (let i = 0; i < 10; i++) {
            num += Math.ceil(Math.random() * 10);
          }
          link.setAttribute("download", "用户_" + num + ".xls");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          NProgress.done();
        })
        .catch(() => {});
    },
    // 新增
    handleIncrease() {
      this.addVisible = true;
    },
    // 审核编辑
    handleChecked(index, row, auditStatus) {
      console.log(index, row, auditStatus);
      this.idx = index;
      this.row = row;
      this.query.auditStatus = auditStatus;

      if (auditStatus == 2) {
        // 不通过
        this.checkedVisible = true;
      } else if (auditStatus == 1) {
        this.checkedVisible == false;
        // 通过
        // 二次确认删除
        this.$confirm("确定要通过吗？", "提示", {
          type: "warning",
        })
          .then(() => {
            this.handleCheckedSave();
          })
          .catch(() => {});
      }
    },
    // 取消审核
    cancelCheckedSave() {
      this.checkedVisible = false;
      this.textarea = "";
    },
    handleCheckedSave() {
      if (!this.textarea.trim() && this.checkedVisible == true) {
        return this.$message.warning({
          message: "请填写审核不通过原因",
          duration: 1500,
        });
      }
      this.$axios
        .put("/village/household", {
          id: this.row.id,
          auditStatus: this.query.auditStatus,
          memo: this.textarea,
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            this.checkedVisible = false;
            this.textarea = "";
            return this.$message.error(res.msg);
          }

          this.checkedVisible = false;
          this.row = null;
          this.query.auditStatus = "";
          this.textarea = "";
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getData({});
        })
        .catch(() => {});
    },
    // 删除操作
    handleDelete(index, row) {
      this.ids = [];
      var ids = this.ids;
      ids[0] = row.id;
      // 二次确认删除
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.delete(ids);
        })
        .catch(() => {});
    },
    delete(ids) {
      console.log(ids);
      this.$axios
        .delete("/village/household", {
          data: ids,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return;
          }
          this.$message.success("操作成功");
          this.ids = [];
          this.getData({});
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      // console.log(val);
      this.query.villageId = "";

      this.ids = [];
      var ids = this.ids;
      val.forEach((item, index) => {
        ids.push(item.id);
      });
    },
    delAllSelection() {
      var ids = this.ids;
      ids = [...new Set(ids)];
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.delete(ids);
        })
        .catch(() => {});
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index;
      this.editVisible = true;
      this.getEditInfo(row.id);
    },
    getEditInfo(id) {
      console.log(id);
      this.$axios.get(`/village/household/${id}`).then(({ data: res }) => {
        console.log("户室信息", res);
        if (res.code != 0) {
          return;
        }
        this.editForm = res.data;
        this.editForm.enableStatus =
          this.editForm.enableStatus !== null
            ? this.editForm.enableStatus.toString()
            : null;

        console.log(this.editForm);
      });
    },
    // 保存编辑
    saveEdit() {
      var bool = util.isEmpty({
        rfid: this.editForm.rfid,
        villageName: this.editForm.villageName,
        buildingNo: this.editForm.buildingNo,
        unitNo: this.editForm.unitNo,
        houseNumber: this.editForm.houseNumber,
      });
      if (bool) {
        return this.$message.warning("必填项不能留空");
      }

      this.$axios
        .put("/village/household", {
          id: this.editForm.id,
          qrCode: this.editForm.qrCode,
          name: this.editForm.name,
          houseNumber: this.editForm.houseNumber,
          rfid: this.editForm.rfid,
          householder: this.editForm.householder,
          mobile: this.editForm.mobile,
          //   villageId: this.editForm.villageId,
          villageName: this.editForm.villageName,
          buildingNo: this.editForm.buildingNo,
          unitNo: this.editForm.unitNo,
          // partyMember: this.editForm.partyMember,
          enableStatus: this.editForm.enableStatus,
          memo: this.editForm.memo,
          auditStatus: this.editForm.auditStatus,
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return this.$message.error(res.msg);
          }
          this.editVisible = false;
          this.$message.success(`修改第 ${this.idx + 1} 行成功`);
          this.getData({});
          console.log(res);
        })
        .catch(() => {});
    },
    // 保存新增
    saveAdd() {
      var bool = util.isEmpty({
        rfid: this.addForm.rfid,
        villageName: this.addForm.villageName,
        buildingNo: this.addForm.buildingNo,
        unitNo: this.addForm.unitNo,
        houseNumber: this.addForm.houseNumber,
      });
      if (bool) {
        return this.$message.warning("必填项不能留空");
      }
      console.log(this.addForm);

      this.$axios
        .post("/village/household", {
          qrCode: this.addForm.qrCode,
          rfid: this.addForm.rfid,
          householder: this.addForm.householder,
          mobile: this.addForm.mobile,
          villageName: this.addForm.villageName,
          buildingNo: this.addForm.buildingNo,
          unitNo: this.addForm.unitNo,
          houseNumber: this.addForm.houseNumber,
          enableStatus: this.addForm.enableStatus,
          memo: this.addForm.memo,
        })
        .then(({ data: res }) => {
          if (res.code != 0) {
            return this.$message.error(res.msg);
          }
          this.addForm = {
            qrCode: "",
            rfid: "",
            householder: "",
            mobile: "",

            villageName: "",
            buildingNo: "",
            unitNo: "",
            houseNumber: "",

            enableStatus: "",
            memo: "",
          };

          this.addForm.enableStatus = "";
          this.addVisible = false;
          this.getData({});
          console.log(res);
        })
        .catch(() => {});
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData({
        villageId: this.query.villageId,
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.$set(this.query, "pageSize", val);
      this.getData({});
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: auto;
}

.handle-input {
  width: auto;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
